//
//  Double+KS.swift
//  KaisafinStockSwift
//
//  Created by administrator on 2019/12/18.
//  Copyright © 2019 administrator. All rights reserved.
//

import Foundation



extension Double {
    
    /**
     向下取第几位小数
     
     - parameter places: 第几位小数 ，1
     
     15.96 * 10.0 = 159.6
     floor(159.6) = 159.0
     159.0 / 10.0 = 15.9
     
     - returns:  15.96 =  15.9
     */
    func f(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return floor(self * divisor) / divisor
    }
    
    /**
     截取到第几位小数
     */
    func toFloor(_ places:Int) -> String {
        let divisor = pow(10.0, Double(places))
        return (floor(self * divisor) / divisor).toString(maxF: places)
    }
    
    func toDecimal(_ decimal:Int) -> Double{
        let divisor = pow(10.0, Double(decimal))
        return (self * divisor).rounded() / divisor
    }
    
    /**
     转化为字符串格式
     
     - parameter minF:
     - parameter maxF:
     - parameter minI:
     
     - returns:
     */
    func toString(_ minF: Int = 0, maxF: Int = 10, minI: Int = 1) -> String {
        let valueDecimalNumber = NSDecimalNumber(value: self)
        let twoDecimalPlacesFormatter = NumberFormatter()
        twoDecimalPlacesFormatter.maximumFractionDigits = maxF
        twoDecimalPlacesFormatter.minimumFractionDigits = minF
        twoDecimalPlacesFormatter.minimumIntegerDigits = minI
        return twoDecimalPlacesFormatter.string(from: valueDecimalNumber)!
    }
    
    func toUnitString(_ minF: Int = 0, maxF: Int = 10, minI: Int = 1, unitKey:[String], unitValue: Int) -> String{
        var unitStr: String = ""
        var index = 0
        var finalDouble = self
        while finalDouble / Double(unitValue) >= 1 && unitKey.count > index {
            unitStr = unitKey[index]
            finalDouble = finalDouble / Double(unitValue)
            index += 1
        }
        
        let valueDecimalNumber = NSDecimalNumber(value: finalDouble)
        let twoDecimalPlacesFormatter = NumberFormatter()
        twoDecimalPlacesFormatter.maximumFractionDigits = maxF
        twoDecimalPlacesFormatter.minimumFractionDigits = minF
        twoDecimalPlacesFormatter.minimumIntegerDigits = minI
        let finalStr = twoDecimalPlacesFormatter.string(from: valueDecimalNumber)! + unitStr
        return finalStr
    }
    
    /// 转为非0字符串
    /// 如果数值为0用replace替代
    func toNonZeroString(_ replace: String = "", minF: Int = 0, maxF: Int = 10, minI: Int = 1) -> String {
        if self == 0 {
            return replace
        } else {
            return toString(minF, maxF: maxF, minI: minI)
        }
    }
    
}
